<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  EyeInvisibleOutlined as CloseEye,
  EyeOutlined,
} from '@ant-design/icons-vue';
import {
  CheckOne,
  Lightning,
  Remind,
  ViewGridDetail,
} from '@icon-park/vue-next';
import { notification } from 'ant-design-vue';

import { useAuthStore } from '#/store';

defineOptions({ name: 'PublicLogin' });

const router = useRouter();
const authStore = useAuthStore();

// 状态控制
const isRegistering = ref(false);
const loading = ref(false);
const showPassword = ref(false);
const showRegisterPassword = ref(false);
const showRegisterConfirmPassword = ref(false);
const generalError = ref('');

// 登录表单数据
const loginForm = reactive({
  usernameOrEmail: '',
  password: '',
  rememberMe: false,
});

// 注册表单数据
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
});

// 表单验证错误
const errors = reactive({
  usernameOrEmail: '',
  password: '',
  registerUsername: '',
  registerEmail: '',
  registerPassword: '',
  registerConfirmPassword: '',
});

// 使用 i 标志优化后的正则
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-z]{2,}$/i;

// 切换密码显示状态
const togglePasswordVisibility = (type: 'confirm' | 'login' | 'register') => {
  if (type === 'login') {
    showPassword.value = !showPassword.value;
  } else if (type === 'register') {
    showRegisterPassword.value = !showRegisterPassword.value;
  } else {
    showRegisterConfirmPassword.value = !showRegisterConfirmPassword.value;
  }
};

// 登录表单验证
const validateLoginForm = () => {
  errors.usernameOrEmail = '';
  errors.password = '';
  generalError.value = '';

  let isValid = true;

  if (!loginForm.usernameOrEmail.trim()) {
    errors.usernameOrEmail = '请输入用户名或邮箱';
    isValid = false;
  }

  if (!loginForm.password.trim()) {
    errors.password = '请输入密码';
    isValid = false;
  } else if (loginForm.password.length < 6) {
    errors.password = '密码长度不能少于6位';
    isValid = false;
  }

  return isValid;
};

// 注册表单验证
const validateRegisterForm = () => {
  errors.registerUsername = '';
  errors.registerEmail = '';
  errors.registerPassword = '';
  errors.registerConfirmPassword = '';
  generalError.value = '';

  let isValid = true;

  if (!registerForm.username.trim()) {
    errors.registerUsername = '请输入用户名';
    isValid = false;
  } else if (registerForm.username.length < 3) {
    errors.registerUsername = '用户名长度不能少于3位';
    isValid = false;
  }

  if (!registerForm.email.trim()) {
    errors.registerEmail = '请输入邮箱';
    isValid = false;
  } else if (!emailRegex.test(registerForm.email)) {
    errors.registerEmail = '请输入有效的邮箱地址';
    isValid = false;
  }

  if (!registerForm.password.trim()) {
    errors.registerPassword = '请输入密码';
    isValid = false;
  } else if (registerForm.password.length < 6) {
    errors.registerPassword = '密码长度不能少于6位';
    isValid = false;
  }

  if (registerForm.password !== registerForm.confirmPassword) {
    errors.registerConfirmPassword = '两次输入的密码不一致';
    isValid = false;
  }

  return isValid;
};

// 处理登录提交
const handleLoginSubmit = async () => {
  if (!validateLoginForm()) {
    return;
  }

  try {
    loading.value = true;
    generalError.value = '';

    await authStore.authLogin({
      username: loginForm.usernameOrEmail,
      password: loginForm.password,
    });

    if (loginForm.rememberMe) {
      localStorage.setItem('remember_username', loginForm.usernameOrEmail);
    } else {
      localStorage.removeItem('remember_username');
    }

    notification.success({
      message: '登录成功',
      description: '欢迎回来！',
      duration: 2,
    });

    router.push('/workspace');
  } catch (error: any) {
    console.error('登录失败:', error);
    generalError.value = error.message || '登录失败，请检查用户名和密码';
    notification.error({
      message: '登录失败',
      description: generalError.value,
      duration: 3,
    });
  } finally {
    loading.value = false;
  }
};

// 处理注册提交
const handleRegisterSubmit = async () => {
  if (!validateRegisterForm()) {
    return;
  }

  try {
    loading.value = true;
    generalError.value = '';

    await authStore.authRegister({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
    });

    notification.success({
      message: '注册成功',
      description: '您的账户已创建，请登录',
      duration: 2,
    });

    isRegistering.value = false;
    loginForm.usernameOrEmail = registerForm.username;
  } catch (error: any) {
    console.error('注册失败:', error);
    generalError.value = error.message || '注册失败，请稍后再试';
    notification.error({
      message: '注册失败',
      description: generalError.value,
      duration: 3,
    });
  } finally {
    loading.value = false;
  }
};

// 检查记住的用户名
const checkRememberedUsername = () => {
  const rememberedUsername = localStorage.getItem('remember_username');
  if (rememberedUsername) {
    loginForm.usernameOrEmail = rememberedUsername;
    loginForm.rememberMe = true;
  }
};

checkRememberedUsername();
</script>

<template>
  <div
    class="f flex min-h-screen items-center justify-center bg-gradient-to-br p-5"
  >
    <div
      class="relative mx-auto flex h-[500px] w-full max-w-4xl overflow-hidden rounded-lg bg-white shadow-xl dark:bg-gray-800"
    >
      <!-- 表单容器 -->
      <div
        class="absolute top-1/2 z-10 flex h-[520px] w-[48%] -translate-y-1/2 flex-col items-center justify-center rounded-lg bg-gray-50 shadow-md transition-all duration-500 dark:bg-gray-700"
        :style="{
          left: isRegistering ? '52%' : '0',
          'margin-left': isRegistering ? '0' : '1%',
        }"
      >
        <!-- 注册表单 -->
        <div class="register-box" :class="[{ hidden: !isRegistering }]">
          <h1>注册</h1>
          <form
            @submit.prevent="handleRegisterSubmit"
            class="space-y-4 sm:space-y-6"
          >
            <!-- 用户名输入框 -->
            <div>
              <label
                for="register-username"
                class="block text-xs font-medium text-gray-700 sm:text-sm"
              >
                用户名
              </label>
              <TextInput
                control-size="large"
                element-id="register-username"
                v-model="registerForm.username"
                type="text"
                required
                :disabled="loading"
                class="mt-1 block w-full sm:mt-2"
                placeholder="请输入用户名"
                autocomplete="username"
              />
              <p
                v-if="errors.registerUsername"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.registerUsername }}
              </p>
            </div>

            <!-- 邮箱输入框 -->
            <div>
              <label
                for="register-email"
                class="block text-xs font-medium text-gray-700 sm:text-sm dark:text-gray-300"
              >
                邮箱
              </label>
              <TextInput
                control-size="large"
                element-id="register-email"
                v-model="registerForm.email"
                type="email"
                required
                :disabled="loading"
                class="mt-1 block w-full sm:mt-2"
                placeholder="请输入邮箱"
                autocomplete="email"
              />
              <p
                v-if="errors.registerEmail"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.registerEmail }}
              </p>
            </div>

            <!-- 密码输入框 -->
            <div>
              <label
                for="register-password"
                class="block text-xs font-medium text-gray-700 sm:text-sm dark:text-gray-300"
              >
                密码
              </label>
              <div class="relative mt-1">
                <TextInput
                  control-size="large"
                  element-id="register-password"
                  v-model="registerForm.password"
                  :type="showRegisterPassword ? 'text' : 'password'"
                  required
                  :disabled="loading"
                  class="mt-1 block w-full sm:mt-2"
                  placeholder="请输入密码"
                  autocomplete="new-password"
                />
                <button
                  type="button"
                  @click="togglePasswordVisibility('register')"
                  class="absolute inset-y-0 right-0 flex items-center pr-3"
                >
                  <EyeOutlined
                    v-if="showRegisterPassword"
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                  <CloseEye
                    v-else
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                </button>
              </div>
              <p
                v-if="errors.registerPassword"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.registerPassword }}
              </p>
            </div>

            <!-- 确认密码输入框 -->
            <div>
              <label
                for="register-confirm-password"
                class="block text-xs font-medium text-gray-700 sm:text-sm dark:text-gray-300"
              >
                确认密码
              </label>
              <div class="relative mt-1">
                <TextInput
                  control-size="large"
                  element-id="register-confirm-password"
                  v-model="registerForm.confirmPassword"
                  :type="showRegisterConfirmPassword ? 'text' : 'password'"
                  required
                  :disabled="loading"
                  class="mt-1 block w-full sm:mt-2"
                  placeholder="请再次输入密码"
                  autocomplete="new-password"
                />
                <button
                  type="button"
                  @click="togglePasswordVisibility('confirm')"
                  class="absolute inset-y-0 right-0 flex items-center pr-3"
                >
                  <EyeOutlined
                    v-if="showRegisterConfirmPassword"
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                  <CloseEye
                    v-else
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                </button>
              </div>
              <p
                v-if="errors.registerConfirmPassword"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.registerConfirmPassword }}
              </p>
            </div>

            <div
              v-if="generalError"
              class="rounded-md bg-red-50 p-3 sm:p-4 dark:bg-red-900/20"
            >
              <div class="flex">
                <Remind class="h-4 w-4 text-red-400 sm:h-5 sm:w-5" />
                <div class="ml-2 sm:ml-3">
                  <p class="text-xs text-red-700 sm:text-sm dark:text-red-400">
                    {{ generalError }}
                  </p>
                </div>
              </div>
            </div>

            <!-- 注册按钮 -->
            <Button
              size="large"
              type="submit"
              :disabled="loading"
              class="w-full items-center justify-center rounded-md text-sm sm:text-base"
            >
              <Spinner
                v-if="loading"
                class="mr-2 h-4 w-4 animate-spin sm:h-5 sm:w-5"
                stroke="currentColor"
              />
              {{ loading ? '注册中...' : '注册' }}
            </Button>

            <!-- 移动端登录按钮 -->
            <div class="mt-4 block sm:hidden">
              <button
                type="button"
                @click="isRegistering = false"
                class="w-full rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
              >
                切换到登录
              </button>
            </div>
          </form>
        </div>

        <!-- 登录表单 -->
        <div class="login-box" :class="[{ hidden: isRegistering }]">
          <h1>登录</h1>
          <form
            @submit.prevent="handleLoginSubmit"
            class="space-y-4 sm:space-y-6"
          >
            <!-- 用户名或邮箱输入框 -->
            <div>
              <label
                for="usernameOrEmail"
                class="block text-xs font-medium text-gray-700 sm:text-sm dark:text-gray-300"
              >
                用户名或邮箱
              </label>
              <TextInput
                control-size="large"
                element-id="usernameOrEmail"
                v-model="loginForm.usernameOrEmail"
                type="text"
                required
                :disabled="loading"
                class="mt-1 block w-full sm:mt-2"
                placeholder="请输入用户名或邮箱"
                autocomplete="username"
              />
              <p
                v-if="errors.usernameOrEmail"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.usernameOrEmail }}
              </p>
            </div>

            <!-- 密码输入框 -->
            <div>
              <label
                for="password"
                class="block text-xs font-medium text-gray-700 sm:text-sm dark:text-gray-300"
              >
                密码
              </label>
              <div class="relative mt-1">
                <TextInput
                  control-size="large"
                  element-id="password"
                  v-model="loginForm.password"
                  :type="showPassword ? 'text' : 'password'"
                  required
                  :disabled="loading"
                  class="mt-1 block w-full sm:mt-2"
                  placeholder="请输入密码"
                  autocomplete="current-password"
                />
                <button
                  type="button"
                  @click="togglePasswordVisibility('login')"
                  class="absolute inset-y-0 right-0 flex items-center pr-3"
                >
                  <EyeOutlined
                    v-if="showPassword"
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                  <CloseEye
                    v-else
                    class="h-4 w-4 text-gray-400 sm:h-5 sm:w-5"
                  />
                </button>
              </div>
              <p
                v-if="errors.password"
                class="mt-1 text-xs text-red-600 sm:text-sm"
              >
                {{ errors.password }}
              </p>
            </div>

            <!-- 记住我 -->
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <CheckBox
                  size="large"
                  id="remember-me"
                  v-model="loginForm.rememberMe"
                  :disabled="loading"
                  class="h-4 w-4 rounded text-blue-600 focus:ring-blue-500"
                />
                <Label
                  for="remember-me"
                  class="ml-2 text-xs text-gray-700 sm:text-sm dark:text-gray-300"
                >
                  记住我
                </Label>
              </div>

              <router-link
                to="/auth/forget-password"
                class="text-xs text-blue-600 hover:text-blue-500 sm:text-sm dark:text-blue-400"
              >
                忘记密码？
              </router-link>
            </div>

            <!-- 移动端注册按钮 -->
            <div class="mt-4 block sm:hidden">
              <button
                type="button"
                @click="isRegistering = true"
                class="w-full rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
              >
                切换到注册
              </button>
            </div>

            <div
              v-if="generalError"
              class="rounded-md bg-red-50 p-3 sm:p-4 dark:bg-red-900/20"
            >
              <div class="flex">
                <Remind class="h-4 w-4 text-red-400 sm:h-5 sm:w-5" />
                <div class="ml-2 sm:ml-3">
                  <p class="text-xs text-red-700 sm:text-sm dark:text-red-400">
                    {{ generalError }}
                  </p>
                </div>
              </div>
            </div>

            <!-- 登录按钮 -->
            <Button
              size="large"
              type="submit"
              :disabled="loading"
              class="w-full items-center justify-center rounded-md text-sm sm:text-base"
            >
              <Spinner
                v-if="loading"
                class="mr-2 h-4 w-4 animate-spin sm:h-5 sm:w-5"
                stroke="currentColor"
              />
              {{ loading ? '登录中...' : '登录' }}
            </Button>
          </form>
        </div>
      </div>

      <!-- 左侧面板 -->
      <div
        class="con-box left ease relative z-[5] flex h-full w-1/2 flex-col items-center justify-center p-10 text-center"
      >
        <h2 class="mb-4 text-2xl font-semibold text-gray-800 dark:text-white">
          欢迎来到<span class="text-primary font-bold dark:text-blue-300">
            文件传输
          </span>
        </h2>
        <p class="mb-8 text-sm text-gray-600 dark:text-gray-300">
          安全快速的文件共享平台
        </p>
        <div class="my-8 flex justify-center gap-5">
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <CheckOne size="24" class="text-primary dark:text-blue-300" />
          </div>
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <Lightning size="24" class="text-primary dark:text-blue-300" />
          </div>
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <ViewGridDetail size="24" class="text-primary dark:text-blue-300" />
          </div>
        </div>
        <p class="mb-4 text-sm text-gray-600 dark:text-gray-300">已有账号</p>
        <button
          id="login"
          @click="isRegistering = false"
          class="border-primary text-primary hover:bg-primary cursor-pointer rounded-full border bg-white px-5 py-2 text-sm font-medium transition-all hover:text-white dark:border-blue-300 dark:bg-gray-800 dark:text-blue-300 dark:hover:bg-blue-300 dark:hover:text-gray-800"
        >
          去登录
        </button>
      </div>

      <!-- 右侧面板 -->
      <div
        class="con-box right ease relative z-[5] flex h-full w-1/2 flex-col items-center justify-center p-10 text-center"
      >
        <h2 class="mb-4 text-2xl font-semibold text-gray-800 dark:text-white">
          欢迎来到<span class="text-primary font-bold dark:text-blue-300">
            文件传输
          </span>
        </h2>
        <p class="mb-8 text-sm text-gray-600 dark:text-gray-300">
          立即注册体验高效文件共享
        </p>
        <div class="my-8 flex justify-center gap-5">
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <CheckOne size="24" class="text-primary dark:text-blue-300" />
          </div>
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <Lightning size="24" class="text-primary dark:text-blue-300" />
          </div>
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 dark:bg-blue-900/30"
          >
            <ViewGridDetail size="24" class="text-primary dark:text-blue-300" />
          </div>
        </div>
        <p class="mb-4 text-sm text-gray-600 dark:text-gray-300">没有账号？</p>
        <button
          id="register"
          @click="isRegistering = true"
          class="border-primary text-primary hover:bg-primary cursor-pointer rounded-full border bg-white px-5 py-2 text-sm font-medium transition-all hover:text-white dark:border-blue-300 dark:bg-gray-800 dark:text-blue-300 dark:hover:bg-blue-300 dark:hover:text-gray-800"
        >
          去注册
        </button>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* 仅保留无法用Tailwind表示的渐变背景 */
.con-box.left {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f7ff 100%);
}

.con-box.right {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f7ff 100%);
}

/* 深色模式下的渐变背景 */
.dark .con-box.left {
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
}

.dark .con-box.right {
  background: linear-gradient(135deg, #4a5568 0%, #2d3748 100%);
}

/* 移动端适配 */
@media (max-width: 650px) {
  .con-box {
    display: none; /* 隐藏背景面板 */
  }

  .absolute {
    width: 100% !important;
    left: 0 !important;
    margin-left: 0 !important;
    box-shadow: none;
    background: transparent !important;
  }

  .login-box,
  .register-box {
    width: 100%;
    padding: 1rem;
  }
}
</style>
